import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'
import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader.js'

var gltfWithDracoLoder = function () {
  const loader = new GLTFLoader()
  const dracoLoader = new DRACOLoader()
  
  // 设置解码路径为绝对路径 注意******
  var url = '/'
  if(process.env.NODE_ENV == 'production'){
    url = '/aihuman/aihumanShow/'
  }
  const decoderPath = `${location.origin}${url}draco/`
  dracoLoader.setDecoderPath(decoderPath)
  
  // 设置DRACO加载器的缓存策略
  dracoLoader.setDecoderConfig({ type: 'js' })
  
  // 配置GLTF加载器使用缓存
  loader.setDRACOLoader(dracoLoader)
  
  // 增强加载器的load方法以添加缓存头
  const originalLoad = loader.load.bind(loader)
  const originalLoadAsync = loader.loadAsync.bind(loader)
  
  // 重写loadAsync以支持进度回调
  loader.loadAsync = function(url, onProgress) {
    return new Promise((resolve, reject) => {
      // 使用原始加载器，让Service Worker处理缓存
      originalLoadAsync(url, onProgress)
        .then(resolve)
        .catch(reject);
    });
  }
  
  return {
    loader,
    dracoLoader
  }
}

export { gltfWithDracoLoder }
